<template>
	<div>
	        	<div id="editor" @paste="paste" v-if="currentCatName!='回收站'">
        			<ul class="_3LYoB clearfix">		
        				<li class="_2zLpt" data-index="0"><a @click="getPos" v-b-modal.modal-center  title="上传图片"><i class="fa fa-picture-o"></i></a></li>
        				<li class="tGbI7 cztJE" data-index="2"><a @click="published"><i class="fa fa-mail-forward"></i> 发布文章</a></li>
        				<li class="_2zLpt tGbI7" data-index="1"><a @click="fullScreen"  :title="isFullScreen?'退出全屏':'全屏'"><i class="fa fa-expand"></i></a></li>
        				<li class="_2zLpt tGbI7" data-index="1"><a title="保存草稿" @click="save"><i class="fa fa-floppy-o"></i></a></li>
        			</ul> 
        			<textarea id="textMarkdown" :value="markdown" @input="update" :style="autoheight"></textarea> 
        			<div id="htmlMarkdown" v-html="compiledMarkdown" :style="autoheight"></div> 
        		</div>
        		<b-modal id="modal-center" @cancel="cancelUpload" @ok="confirmUpload" cancel-title="取消" ok-title="确定" centered title="上传图片">
        		    <p class="my-4">
        		    	<b-form-file capture multiple ref="fileinput" v-model="files" :state="Boolean(files)" placeholder="Choose a file..."></b-form-file>
                  <div ref="select_frame" class="drop_box">
                      将文件拖拽到这里
                  </div>
        		    	<span v-if="selectFile">
        		    		<img style="width:100px" v-for="img in imgs" :src="img.src" :title="img.name"/>
        		    	</span>
        		    </p>
        		</b-modal>
    </div>
</template>

<script>
var tmpheight=document.documentElement.clientHeight;
var newheight='height:'+(tmpheight-83)+'px';
var fullheight='height:'+(tmpheight-45)+'px';
var myMarked = require('marked');
import 'highlight.js/styles/github.css';
// Set options
// `highlight` example uses `highlight.js`
myMarked.setOptions({
  renderer: new myMarked.Renderer(),
  highlight: function(code) {
    return require('highlight.js').highlightAuto(code).value;
  },
  pedantic: false,
  gfm: true,
  tables: true,
  breaks: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  xhtml: false
});
(function ($, undefined) {
    $.fn.getCursorPosition = function () {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);


export default {
	props: ['input','currentCatName'],
	data(){
	  return {
            isFullScreen:false,
			imgs:[],
			autoheight:newheight,
			markdown:this.input,
			loadLocalStorage:false,
			pos:0,
    		files:null
      }
    },
    watch: {
        input(val) {
        	this.markdown = val;//新增input的watch，监听变更并同步到markdown上
        }
    },
    mounted(){

    	 this.$refs.select_frame.ondragleave = (e) => {
	      e.preventDefault();  //阻止离开时的浏览器默认行为
	    };
	    this.$refs.select_frame.ondrop = (e) => {
	      e.preventDefault();    //阻止拖放后的浏览器默认行为
	      const data = e.dataTransfer.files;  // 获取文件对象
	      if (data.length < 1) {
	        return;  // 检测是否有文件拖拽到页面     
	      }
	      this.files=data;
	    };
	    this.$refs.select_frame.ondragenter = (e) => {
	      e.preventDefault();  //阻止拖入时的浏览器默认行为
	      this.$refs.select_frame.border = '2px dashed red';
	    };
	    this.$refs.select_frame.ondragover = (e) => {
	      e.preventDefault();    //阻止拖来拖去的浏览器默认行为
	    };
    },
    computed:{
        compiledMarkdown: function () {     
	      return myMarked(this.markdown);
	    },
	    selectFile: function(){
	      if(this.files && this.files.length>0){
	        let name='';
	        let imgs=[];
	        _.forEach(this.files,function(file){
	          var reader  = new FileReader();
	          reader.addEventListener("load", function () {
	            imgs.push({name:file.name,src:reader.result});
	            console.log('load...'+file.name+_.now());
	          }, false);
	          reader.readAsDataURL(file);
	          name=name+file.name;
	        })
	        this.imgs=imgs;
	        return true;
	      }else{
	        return false;
	      }
	    }
    },
    methods:{
    	fullScreen:function(e){
	          if(this.isFullScreen){
	            this.autoheight=newheight;
	          }else{
	            this.autoheight=fullheight;
	          }
	          this.isFullScreen=!this.isFullScreen;
	          this.$emit('syncData',{isFullScreen:this.isFullScreen});
	     },
	     paste:function(event){
	        var pos = $('#editor textarea').getCursorPosition();
	        var clipboard = event.clipboardData || event.originalEvent.clipboardData;
	        var type = clipboard.items[0].type;
	        var blob=null;
	        if (type.match(/image/)) {
	            blob = clipboard.items[0].getAsFile();            
	        }else{
	          _.forEach(clipboard.items,function(item){
	            console.log(item.type+item.kind);
	            if(item.type==='image/png'){
	              blob=item.getAsFile();
	              return;
	            }
	          });
	        }
	        if(blob!==null){
	            var formdata=new FormData();// 创建form对象
	            formdata.append('img_0',blob);// 通过append向form对象添加数据,可以通过append继续添加数据
	            formdata.append('filesCount',1);
	            let config = {
	              headers:{'Content-Type':'multipart/form-data'}
	            };  //添加请求头
	            var that=this;
	            axios.post('/rbac/file/apiUpload',formdata,config)
	              .then(function (response) { 
	                var imgFiles=response.data;
	                var imgFilesString='';
	                _.forEach(imgFiles,function(file){
	                  imgFilesString=imgFilesString+'![default]('+file+')';
	                });
	                var textarea_content=that.markdown;
	                textarea_content=textarea_content.substring(0,pos)+imgFilesString+textarea_content.substring(pos);
	                localStorage.setItem('markdown',textarea_content);
	                that.markdown=textarea_content; 
	                this.$emit('syncData',{markdown:textarea_content,htmlContent:that.compiledMarkdown});           
	              })
	              .catch(function (error) {
	                console.log(error);
	              });
	            event.preventDefault();
	        }

	   },
	    update: _.debounce(function (e) {
	       this.markdown = e.target.value;
	       localStorage.setItem('markdown',e.target.value);
	     }, 300),
	  uploadFiles:function(files){
      var that=this;
      var formdata=new FormData();// 创建form对象
      var filesCount=files.length;
      for (var i = 0; i <= filesCount-1; i++) {
        formdata.append('img_'+i,files[i]);// 通过append向form对象添加数据,可以通过append继续添加数据
      }
      formdata.append('filesCount',filesCount);
      let config = {
          headers:{'Content-Type':'multipart/form-data'}
      };  //添加请求头
      axios.post('/rbac/file/apiUpload',formdata,config)
        .then(function (response) { 
          var imgFiles=response.data;
          var imgFilesString='';
          _.forEach(imgFiles,function(file){
            imgFilesString=imgFilesString+'![default]('+file+')';
          });
          var textarea_content=that.markdown.substring(0,that.pos)+imgFilesString+that.markdown.substring(that.pos);
          localStorage.setItem('markdown',textarea_content);
          that.markdown=textarea_content;
          this.$emit('syncData',{markdown:textarea_content,htmlContent:that.compiledMarkdown});
          that.$refs.fileinput.reset();
        })
        .catch(function (error) {
          console.log(error);
        });
     },
     confirmUpload:function(){
     	  this.uploadFiles(this.files);
     },
     cancelUpload:function(){
     	this.$refs.fileinput.reset();
     },
     getPos:function(){
     	var index = $('#editor textarea').getCursorPosition();
     	console.log(index);
     	this.pos=index;
     },
     published:function(){
     	var data={htmlContent:this.compiledMarkdown,markdown:this.markdown,isFullScreen:false};
     	this.$emit('syncData',data);
        this.$emit('publishedAction');
        localStorage.setItem('markdown','');
     },
     save:function(){
     	var data={htmlContent:this.compiledMarkdown,markdown:this.markdown,isFullScreen:false};
     	this.$emit('syncData',data);
     	this.$emit('saveAction');
     	localStorage.setItem('markdown','');
     },


    }
}
</script>